<template>
  <view class="volunteer-detail-container">
    <!-- 活动头部信息 -->
    <view class="activity-header">
      <view class="title-section">
        <text class="title">{{ item.title }}</text>
        <view class="status-badge" :class="{'recruiting': item.state === 1, 'ended': item.state !== 1}">
          {{ item.state === 1 ? '招募中' : '已结束' }}
        </view>
      </view>
      <text class="create-time">{{ formattedCreateTime }}</text>
    </view>

    <!-- 分隔线 -->
    <view class="divider"></view>

    <!-- 基本信息 -->
    <view class="basic-info">
      <view class="info-item">
        <uni-icons type="location-filled" size="16" color="#666"></uni-icons>
        <text class="info-text">{{ formattedLocation }}</text>
      </view>
      <view class="info-item">
        <uni-icons type="phone" size="16" color="#666"></uni-icons>
        <text class="info-text">{{ item.contactInfo }}</text>
      </view>
      <view class="info-item">
        <uni-icons type="person" size="16" color="#666"></uni-icons>
        <text class="info-text">发起人：{{ item.creator }}</text>
      </view>
    </view>

    <!-- 分隔线 -->
    <view class="divider"></view>

    <!-- 活动内容 -->
    <view class="content-section">
      <text class="content-title">活动详情</text>
      <view class="content-text">{{ item.content }}</view>
    </view>

    <!-- 活动图片 -->
    <view class="image-gallery" v-if="images.length > 0">
      <view class="gallery-title">活动图片</view>
      <scroll-view class="image-list" scroll-x>
        <image
          v-for="(image, index) in images"
          :key="index"
          :src="image"
          mode="aspectFill"
          class="gallery-image"
          @click="previewImage(index)"
        />
      </scroll-view>
    </view>

    <!-- 参与者信息（仅创建者可见） -->
    <view class="participants-section" v-if="myKey == '1'">
      <view class="section-title">
        <uni-icons type="group" size="16" color="#666"></uni-icons>
        <text>参与情况</text>
      </view>
      <view class="participants-count">
        <text>已报名：{{ participantsCount }}人</text>
      </view>
      <view class="participants-list">
        <text class="list-title">报名用户：</text>
        <text v-for="(participant, index) in participants" :key="index" class="participant-name">
          {{ participant }}{{ index < participants.length - 1 ? '，' : '' }}
        </text>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="action-buttons">
      <!-- 普通用户看到的按钮 -->
      <template v-if="!isMine && item.state === 1">
        <button
          class="action-btn join-btn"
          @click="handleJoin"
          v-if="!isJoined"
        >
          <uni-icons type="plus" size="16" color="#fff"></uni-icons>
          <text>立即报名</text>
        </button>
        <button
          class="action-btn joined-btn"
          disabled
          v-else
        >
          <uni-icons type="checkmark" size="16" color="#fff"></uni-icons>
          <text>已报名</text>
        </button>
      </template>

      <!-- 创建者看到的按钮 -->
      <template v-if="isMine && myKey == '1'">
        <button
          class="action-btn end-btn"
          @click="handleEnd"
          v-if="item.state === 1"
        >
          <uni-icons type="flag" size="16" color="#fff"></uni-icons>
          <text>结束活动</text>
        </button>
        <button
          class="action-btn ended-btn"
          disabled
          v-else
        >
          <uni-icons type="info" size="16" color="#fff"></uni-icons>
          <text>活动已结束</text>
        </button>
      </template>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      item: {},
      images: [],
      myKey: '',
      isJoined: false,
      isMine: false,
      participantsCount: 0,
      participants: [],
    };
  },
  props: {
    activityOptions: {
      type: Object,
      default: () => ({}),
    },
  },
  mounted() {
    this.getActivityDetails(this.activityOptions.query);
    this.getImages(this.activityOptions.query);
    this.initIsJoined(this.activityOptions.query);
    this.myKey = this.activityOptions.myKey;
    if(this.myKey == '1') this.getAllParticipants(this.activityOptions.query);
  },
  computed: {
    formattedCreateTime() {
      if (!this.item.createTime) return '';
      const date = new Date(this.item.createTime);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },
    formattedLocation() {
      if(this.item.province === this.item.city) {
        return `${this.item.city}${this.item.region}${this.item.detail}`;
      }
      return `${this.item.province}${this.item.city}${this.item.region}${this.item.detail}`;
    }
  },
  methods: {
    async getAllParticipants(activity_id) {
      const { data: res } = await uni.$http.get('/user/participants', {
        activityId: activity_id,
      });
      if(res.code !== 1) return uni.$showMsg();
      this.participants = res.data;
      this.participantsCount = this.participants.length;
    },
    async initIsJoined(activity_id) {
      const { data: res } = await uni.$http.get('/activities/isjoin', {
        activityId: activity_id,
      });
      if(res.code !== 1) return uni.$showMsg();
      this.isJoined = res.data != null;
    },
    async handleJoin() {
      try {
        await this.joinActivity(this.item.id);
        this.isJoined = true;
        uni.showToast({
          title: '报名成功',
          icon: 'success'
        });
      } catch (error) {
        uni.showToast({
          title: '报名失败',
          icon: 'none'
        });
      }
    },
    async handleEnd() {
      try {
        await this.endActivity(this.item.id);
        this.item.state = 0;
        uni.$showMsg("活动已结束");
      } catch (error) {
        uni.$showMsg("操作失败");
      }
    },
    async endActivity(activityId) {
      const { data: res } = await uni.$http.post('/activities/end', {
        activityId: activityId,
      });
      if (res.code !== 1) throw new Error(res.message);
      return res.data;
    },
    async joinActivity(activityId) {
      const { data: res } = await uni.$http.post('/activities/join', {
        activityId: activityId,
      });
      if (res.code !== 1) throw new Error(res.message);
      return res.data;
    },
    previewImage(index) {
      uni.previewImage({
        current: index,
        urls: this.images,
        indicator: "default"
      });
    },
    async getActivityDetails(id) {
      const { data: res } = await uni.$http.get('/activities/detail', {
        activity_id: id
      });
      if (res.code !== 1) return uni.$showMsg();
      this.item = res.data;
      this.isMine = this.item.openid === 'yes';
    },
    async getImages(id) {
      const { data: res } = await uni.$http.get('/activities/images', {
        activity_id: id
      });
      if (res.code !== 1) return uni.$showMsg();
      this.images = res.data;
    }
  }
}
</script>

<style lang="scss">
.volunteer-detail-container {
  padding: 24rpx;
  padding-bottom: 120rpx;
  background-color: #f7f7f7;
  min-height: 100vh;

  .activity-header {
    margin-bottom: 24rpx;
    
    .title-section {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;
      
      .title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        flex: 1;
      }
      
      .status-badge {
        padding: 6rpx 16rpx;
        border-radius: 20rpx;
        font-size: 24rpx;
        margin-left: 16rpx;
        
        &.recruiting {
          background-color: #e1f3d8;
          color: #67c23a;
        }
        
        &.ended {
          background-color: #fde2e2;
          color: #f56c6c;
        }
      }
    }
    
    .create-time {
      font-size: 24rpx;
      color: #999;
    }
  }

  .divider {
    height: 2rpx;
    background-color: #eee;
    margin: 24rpx 0;
  }

  .basic-info {
    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      font-size: 28rpx;
      color: #333;
      
      .info-text {
        margin-left: 10rpx;
      }
    }
  }

  .content-section {
    margin-bottom: 32rpx;
    
    .content-title {
      display: block;
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 16rpx;
    }
    
    .content-text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.8;
      text-align: justify;
      text-indent: 2em;
    }
  }

  .image-gallery {
    margin-bottom: 32rpx;
    
    .gallery-title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 16rpx;
    }
    
    .image-list {
      white-space: nowrap;
      
      .gallery-image {
        width: 200rpx;
        height: 200rpx;
        border-radius: 8rpx;
        margin-right: 16rpx;
      }
    }
  }

  .participants-section {
    background-color: #f9f9f9;
    border-radius: 12rpx;
    padding: 24rpx;
    margin-bottom: 32rpx;
    
    .section-title {
      display: flex;
      align-items: center;
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 16rpx;
      
      text {
        margin-left: 8rpx;
      }
    }
    
    .participants-count {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 12rpx;
    }
    
    .participants-list {
      font-size: 28rpx;
      color: #666;
      
      .list-title {
        color: #333;
      }
      
      .participant-name {
        display: inline-block;
        margin-right: 8rpx;
      }
    }
  }

  .action-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.1);
    display: flex;
    
    .action-btn {
      flex: 1;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border: none;
      
      uni-icons {
        margin-right: 8rpx;
      }
      
      &.join-btn {
        background: linear-gradient(to right, #67c23a, #5daf34);
        color: #fff;
      }
      
      &.joined-btn {
        background-color: #909399;
        color: #fff;
      }
      
      &.end-btn {
        background: linear-gradient(to right, #f56c6c, #e64e4e);
        color: #fff;
      }
      
      &.ended-btn {
        background-color: #909399;
        color: #fff;
      }
    }
  }
}
</style>